package com.lin.services.impl;

import com.lin.dao.CategoryDao;
import com.lin.dao.PromotionDao;
import com.lin.dao.UserDao;
import com.lin.dao.WaresDao;
import com.lin.pojo.Promotion;
import com.lin.pojo.Wares;
import com.lin.services.PromotionService;
import com.lin.utils.ShiroUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class PromotionServiceImpl implements PromotionService {
    @Autowired
    private PromotionDao promotionDao;
    @Autowired
    private WaresDao waresDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CategoryDao categoryDao;

    @Override
    public List<Wares> getPromotionWares(Integer promotionId, Date endDate, String data) {
        promotionDao.updatePromotionStatus(ShiroUtil.getUser().getStoreId());
        Promotion promotionInfo = promotionDao.findPromotionById(promotionId, ShiroUtil.getUser().getStoreId());
        String type = promotionInfo.getType();
        List<Wares> lists = new ArrayList<>();
        if (("特价分类".equals(type) || "特价商品".equals(type)) && (data == null || "".equals(data.trim()))) {
            return null;
        }
        String[] strings = data.split(",");
        for (String str : strings) {
            lists.addAll(promotionDao.findAllWaresWhichCan(promotionInfo.getType(), str, ShiroUtil.getUser().getStoreId()));
        }
        List<Integer> waresIdList = promotionDao.getPromotionWaresId(promotionId);
        for (Wares list : lists) {
            list.setExpiryDate(promotionId);
            list.setStatus(0);
            for (Integer pId : waresIdList) {
                if (pId.equals(list.getId())) {
                    list.setStatus(1);
                }
            }
        }
        return lists;
    }

    @Override
    public List<Wares> findPromotionWaresById(String waresId) {
        List<Wares> list = new ArrayList<>();
        if (waresId != null && !"".equals(waresId.trim())) {
            list = waresDao.getWarsList(waresId.trim(), "", "", "", ShiroUtil.getUser().getStoreId());
        }
        return list;
    }

    @Override
    public Map<String, Object> insertPromotion(Map<String, String[]> map) {
        Promotion promotionInfo = new Promotion();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", false);
        resultMap.put("msg", "活动创建失败");
        Set<String> keySet = map.keySet();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss");
        String type = map.get("type")[0];
        promotionInfo.setType(type);
        promotionInfo.setDescribe("暂无说明");
        promotionInfo.setStoreId(ShiroUtil.getUser().getStoreId());
        for (String key : keySet) {
            String[] values = map.get(key);
            for (String value : values) {
                if (!"promotionDescribe".equals(key) && (value == null || "".equals(value.trim()))) {
                    resultMap.put("msg", "表单数据异常");
                    return resultMap;
                }
                if ("promotionName".equals(key)) {
                    promotionInfo.setName(value);
                }
                if ("promotionDescribe".equals(key) && value != null && !"".equals(value.trim())) {
                    promotionInfo.setDescribe(value);
                }
                if ("promotionDate".equals(key)) {
                    String[] dateStr = value.split(" - ");
                    try {
                        promotionInfo.setStartDate(sdf1.parse(dateStr[0]));
                        promotionInfo.setEndDate(sdf1.parse(dateStr[1]));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                if ("promotionTime".equals(key)) {
                    String[] timeStr = value.split(" - ");
                    try {
                        if (sdf2.parse(timeStr[0]).before(sdf2.parse(timeStr[1]))) {
                            promotionInfo.setStartTime(sdf2.parse(timeStr[0]));
                            promotionInfo.setEndTime(sdf2.parse(timeStr[1]));
                        } else {
                            promotionInfo.setStartTime(sdf2.parse(timeStr[1]));
                            promotionInfo.setEndTime(sdf2.parse(timeStr[0]));
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        promotionInfo.setCreator(ShiroUtil.getUserId());
        promotionDao.insertPromotion(promotionInfo);
        Integer promotionId = promotionInfo.getId();
        if (promotionId != null) {
//            设置活动规则
            String[] valuesM1 = map.get("promotionMoney1");
            String[] valuesM2 = map.get("promotionMoney2");
            List<Wares> list = new ArrayList<>();
            for (int i = 0; i < valuesM1.length; i++) {
                if ("限时满减".equals(type)) {
                    if (Float.parseFloat(valuesM1[i]) > Float.parseFloat(valuesM2[i]) && Float.parseFloat(valuesM2[i]) > 0) {
                        promotionDao.insertPromotionRule(type, promotionId, valuesM1[i], valuesM2[i]);
                    }
                } else {
                    promotionDao.insertPromotionRule(type, promotionId, valuesM1[i], valuesM2[i]);
                }
                //设置活动商品
                if ("特价商品".equals(type)) {
                    String waresId = valuesM1[i].split(" - ")[0];
                    Wares waresById = waresDao.findWaresById(Integer.parseInt(waresId), ShiroUtil.getUser().getStoreId());
                    if (waresById == null) {
                        resultMap.put("msg", "商品不存在");
                        return resultMap;
                    }
                }
                list.addAll(promotionDao.findAllWaresWhichCan(promotionInfo.getType(), valuesM1[i], ShiroUtil.getUser().getStoreId()));
            }
            for (Wares wares : list) {
                promotionDao.insertPromotionWares(promotionId, wares.getId());
            }
            resultMap.clear();
            resultMap.put("code", true);
            resultMap.put("type", type);
            resultMap.put("promotionId", promotionId);
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> insertPromotionWares(String promotionIds, String waresIds) {
        Map<String, Object> map = new HashMap<>();
        map.put("msg", "无效操作");
        map.put("code", false);
        if (waresIds == null || "".equals(waresIds.trim()) || promotionIds == null || "".equals(promotionIds.trim())) {
            return map;
        }
        Integer promotionId = Integer.parseInt(promotionIds);
        Integer waresId = Integer.parseInt(waresIds);
        List<Integer> list = promotionDao.selectPromotionWares(promotionId, waresId);
        if (list == null || list.isEmpty()) {
            promotionDao.insertPromotionWares(promotionId, waresId);
            map.clear();
            map.put("code", true);
        }
        return map;
    }

    @Override
    public Map<String, Object> deletePromotionWares(String promotionIds, String waresIds) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", false);
        map.put("msg", "无效操作");
        if (waresIds == null || "".equals(waresIds.trim()) || promotionIds == null || "".equals(promotionIds.trim())) {
            return map;
        }
        Integer waresId = Integer.parseInt(waresIds);
        Integer promotionId = Integer.parseInt(promotionIds);
        int i = promotionDao.deletePromotionWares(promotionId, waresId);
        if (i > 0) {
            map.clear();
            map.put("code", true);
        }
        return map;
    }

    @Override
    public List<Promotion> getPromotion(Map<String, String[]> condition) {
        Set<String> keys = condition.keySet();
        promotionDao.updatePromotionStatus(ShiroUtil.getUser().getStoreId());
        String searchName = null;
        String searchType = null;
        String searchStartDate = null;
        String searchEndDate = null;
        String searchStatus = null;
        for (String key : keys) {
            String value = condition.get(key)[0];
            if (key.equals("promotionSearchName") && value != null && !"".equals(value.trim())) {
                searchName = value;
            }
            if (key.equals("promotionSearchType") && value != null && !"".equals(value.trim()) && !"all".equals(value)) {
                searchType = value;
            }
            if (key.equals("promotionSearchDate") && value != null && !"".equals(value.trim())) {
                String[] times = value.split(" - ");
                searchStartDate = times[0];
                searchEndDate = times[1];
            }
            if (key.equals("promotionSearchStatus") && value != null && !"".equals(value.trim()) && !"all".equals(value)) {
                searchStatus = value;//未开始进行中已结束
            }
        }
        List<Promotion> promotionList = promotionDao.getPromotion(searchName, searchType,
                searchStartDate, searchEndDate, searchStatus, ShiroUtil.getUser().getStoreId());
        for (Promotion promotion : promotionList) {
            promotion.setCreatorName(userDao.getUserById(promotion.getCreator()).getName());
        }
        return promotionList;
    }

    @Override
    public Map<String, Object> promotionOperation(String promotionIds, String toolType) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", false);
        map.put("msg", "操作失败");
        if (promotionIds == null || "".equals(promotionIds.trim())) {
            return map;
        }
        if (toolType == null || "".equals(toolType.trim())) {
            return map;
        }
        Integer promotionId = Integer.parseInt(promotionIds);
        if ("endPromotionInfoSearch".equals(toolType)) {
            int i = promotionDao.updatePromotionMark(promotionId,ShiroUtil.getUser().getStoreId());
            if (i == 1) {
                map.clear();
                map.put("code", true);
            }
        }
        if ("delPromotionInfoSearch".equals(toolType)) {
            int i = promotionDao.deletePromotionInfo(promotionId,ShiroUtil.getUser().getStoreId());
            if (i == 1) {
                map.clear();
                map.put("code", true);
            }
        }
        return map;
    }

    @Override
    public List<Map<String, Object>> getPromotionDetails(String promotionId) {
        List<Map<String, Object>> list = promotionDao.getPromotionRule(promotionId);
        for (Map<String, Object> map1 : list) {
            if ("特价分类".equals(map1.get("promotion_type"))) {
                String name = categoryDao.getCategoryNameById(map1.get("first").toString(),ShiroUtil.getUser().getStoreId());
                map1.put("first", name);
            }
        }
        return list;
    }
}
